﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FazaDemo.BL.InterfaceDomain;
using FazaDemo.BL.SubDomains;

namespace FazaDemo.BL.Services_
{
    class MenuItemsOptimizer
    {

        private IList<Menu_Item> _curItems;

        private readonly int[] _incorrectNums = { 77, 9, 100 };

        private readonly int[] _needNums = { 7, 10, 9 };

        private readonly string[] _winChildsTexts =
        {
            "technology - л/с edit", 
            "л/с", 
            "режим \"один л/с\"", 
            "Формирование файла обмена"
        };

        private const int WinItemId = 8;

        public MenuItemsOptimizer(IList<Menu_Item> curItems)
        {
            _curItems = curItems;
        }

        public IList<Menu_Item> RestoreItems()
        {
            for (int i = 0; i < _needNums.Length; i++)
            {
                RestoreNumeration(_incorrectNums[i], _needNums[i]);
            }
            DeleteWorms();
            return _curItems.OrderBy(i => i.Id).ToList();
        }

        private void RestoreNumeration(int oldNum, int newNum)
        {
            RestoreIds(oldNum, newNum);
            SetWinItemChilds();
        }

        private void DeleteWorms()
        {
            _curItems = _curItems.Where(i => i.Text != "-").ToList();
        }

        private void RestoreIds(int oldNum, int newNum)
        {
            _curItems[_curItems.IndexOf(_curItems.First(n => n.Id == oldNum))].Id = newNum;
            foreach (var item in _curItems.Where(item => item.ParentId == oldNum))
            {
                item.ParentId = newNum;
            }
        }

        private void SetWinItemChilds()
        {
            foreach (var item in _curItems.Where(item => _winChildsTexts.Contains(item.Text)))
            {
                item.ParentId = WinItemId;
            }
        }
    }
}
